package com.up.selfshop.res;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.up.selfshop.util.SignUtil;

public class Res {
	private int code = 0;
	private String msg = "ok";
	private long timestamp = System.currentTimeMillis();
	private String sign;
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public long getTimestamp() {
		return timestamp;
	}
	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}
	public String getSign() {
		return sign;
	}
	public void setSign(String sign) {
		this.sign = sign;
	}
	public String sign() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("code", String.valueOf(code));
		map.put("msg", msg);
		map.put("timestamp", String.valueOf(timestamp));
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			String name = field.getName();
			if ("sign".equals(name)) {
				continue;
			}
			if (Modifier.isTransient(field.getModifiers())) {
				continue;
			}
			Object value = getFieldValueByName(name, this);
			if (value == null || "".equals(value)) {
				continue;
			}
			map.put(name, JSON.toJSONString(value));
		}
		return this.sign = SignUtil.sign(map);
	}
	private Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter);
			Object value = method.invoke(o);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public <T extends Res> T signed() {
		sign();
		return (T) this;
	}
}
